package com.fhc.usb


import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.os.Build
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber


interface UsbDeviceListener {
    fun onUsbDeviceAttached(device: UsbDevice)
    fun onUsbDeviceDetached(device: UsbDevice)
}


class UsbDeviceReceiver(private val listener: UsbDeviceListener? = null) : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == UsbManager.ACTION_USB_DEVICE_DETACHED) {
            val device: UsbDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
            } else {
                @Suppress("DEPRECATION")
                intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
            }
            UsbSerialManager.instance()?.closeDevice()
            if (device != null) {
                // 在这里处理设备拔出逻辑
                Timber.e("USB设备拔出: ${device.deviceName}")

                listener?.onUsbDeviceDetached(device)
            }
        }else if (intent.action == UsbManager.ACTION_USB_DEVICE_ATTACHED) {
            val device: UsbDevice? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                intent.getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)
            } else {
                @Suppress("DEPRECATION")
                intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
            }
            if (device != null) {

                CoroutineScope(Dispatchers.Default).launch {
                    listener?.onUsbDeviceAttached(device)
                    //User has not given 10409/com.fhc.app permission to access device
//                    val a = EventDataUsb()
//                    a.device = UsbDeviceDto.from(device)
                }


                // 在这里处理设备拔出逻辑
                Timber.e("USB设备ATTACHED: ${device.deviceName}")

            }
        }
    }
}